import {transformI18n} from "@/plugins/i18n";
import type {PaginationProps} from "@pureadmin/table";
import {MaBangStatistics} from "@/api/statistics";
import {getSalesList} from "@/api/crm";
import {onMounted, reactive, ref, type Ref, toRaw} from "vue";
import * as XLSX from "xlsx";

export function useAccount(tableRef: Ref) {
  const form = reactive({
    // utm_source: "",
    tab_id: "0",
    search_field2: "time_bj",
    // audit_status: "3",
    time:[]
  });
  const curRow = ref();
  const searchData = ref([]);
  const dataList = ref([]);
  const statusList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const salesman_arr = ref([]);


  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,pageSizes: [20, 40, 60,100,300,500],
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {label: "类别", prop: "type",width:105,showOverflowTooltip:true,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"+row.color):''}>{row.type}</span>
      )},
    {label: "名称", prop: "name",width:105,showOverflowTooltip:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"+row.color):''}>{row.name}</span>
      )},

    // 待处理订单数据
    {label: "待处理订单数", prop: "finished", width: 130,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"):''}>{row.finished||0}</span>
      )},
    {label: "待处理成交量", prop: "finished_performance_count", width: 130,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"):''}>{row.finished_performance_count||0}</span>
      )},
    {label: "待处理成交金额", prop: "finished_sa", width: 150,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"):''}>{row.finished_sa.toFixed(2)||0}</span>
      )},
    {label: "待处理转化率", prop: "finished", width: 150,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:")+row.color:''}>{ formatPercentage(row.finished_performance_count,row.finished) }</span>
      )},
    {label: "待处理均单价", prop: "finished", width: 150,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"):''}>{ formatAvg(row.finished_sa,row.finished)}</span>
      )},

    // 弃单订单数据
    {label: "弃单订单数", prop: "qidan", width: 105,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"):''}>{row.qidan||0}</span>
      )},
    {label: "弃单成交量", prop: "qidan_performance_count", width: 105,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"):''}>{row.qidan_performance_count||0}</span>
      )},
    {label: "弃单成交金额", prop: "qidan_sa", width: 150,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"):''}>{row.qidan_sa.toFixed(2)||0}</span>
      )},
    {label: "弃单转化率", prop: "qidan", width: 105,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:")+row.color:''}>{ formatPercentage(row.qidan_performance_count,row.qidan) }</span>
      )},
    {label: "弃单均单价", prop: "qidan", width: 105,sortable:true,cellRenderer: ({ row, index }) => (
        <span style={row.color?("font-weight: bold;color:"):''}>{ formatAvg(row.qidan_sa,row.qidan) }</span>
      )},
  ];


  function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
  const today = new Date();
  const last30Days = new Date(today);
  last30Days.setDate(today.getDate() - 29);
  // form.time = [formatDate(last30Days),formatDate(today)]
  form.time = [formatDate(today),formatDate(today)]

  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  //处理百分比
  function formatPercentage(molecule, denominator) {
      if (denominator == 0 || denominator == null) return '-';
      if (molecule == 0 || molecule == null) return '0%';

      const percentage = (molecule / denominator) * 100;
      return percentage.toFixed(2) + '%';
    }

  //处理均值
  function formatAvg(molecule, denominator) {
    if (denominator == 0 || denominator == null) return '-';
    if (molecule == 0 || molecule == null) return '0';

    const avg = (molecule / denominator);
    return avg.toFixed(2);
  }



  const getSalemanList = async function (page=1,limit=1000) {
    const {data} = await getSalesList({page,limit}); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    salesman_arr.value = data?.data;
  }
  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  const ApiData = ref([]);

  async function onSearch() {
    loading.value = true;

    const response = await MaBangStatistics(toRaw(form), 'get');
    const data = response.data;
    ApiData.value = data?.list || [];
    dataList.value = data?.list?.[0] || [];

    searchData.value = data?.searchBarData || {};

    filterData()
    // statusList.value = data.status_arr;
    // searchCondList.value = data?.search_cond_arr;
    // pagination.total = data.total;
    // pagination.pageSize = data.per_page;
    // pagination.currentPage = data.currentPage;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  function filterData(){

    dataList.value = ApiData.value[form.tab_id]||[];
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };





  /** 数据权限 可自行开发 */
  const searchCondList =  ref([])




  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    onSearch();
    getSalemanList();
  });


  const exportExcel = () => {
    try {
      const tableEl = tableRef.value.$el
      // 克隆表格（避免影响原表格）
      const clonedTable = tableEl.cloneNode(true)
      // 处理模板内容（转换为纯文本）
      const processTemplates = (node) => {
        // 处理el-tag
        const tags = node.querySelectorAll('.el-tag')
        tags.forEach(tag => {
          tag.outerHTML = tag.textContent
        })
        // 处理el-switch
        const switches = node.querySelectorAll('.el-switch')
        switches.forEach(sw => {
          const isActive = sw.querySelector('.is-active')
          sw.outerHTML = isActive ? '启用' : '禁用'
        })
        // 处理自定义内容（如头像+文本）
        const customContents = node.querySelectorAll('.el-avatar')
        customContents.forEach(avatar => {
          const parent = avatar.parentNode
          parent.outerHTML = parent.textContent.replace(/\s+/g, ' ').trim()
        })

        // 移除操作按钮等不需要的元素
        const buttons = node.querySelectorAll('.el-button')
        buttons.forEach(btn => btn.remove())
      }
      processTemplates(clonedTable)
      // 转换为工作表
      const ws = XLSX.utils.table_to_sheet(clonedTable)
      // 创建工作簿并导出
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      XLSX.writeFile(wb, '马帮转化率统计_'+form.tab_id+'_'+form.time+'.xlsx')
    } catch (error) {
      console.error('导出失败:', error)
    } finally {
    }
  };




  return {
    form, isShow, curRow, loading, columns, dataList, isLinkage, pagination, isExpandAll, isSelectAll,
    statusList,salesman_arr,searchData,
    onSearch, resetForm,filterData,exportExcel,
    searchCondList,
    filterMethod, transformI18n, handleSizeChange,
    handleCurrentChange,
    // 添加缺失的属性
    rowStyle: () => ({}),
    selectedNum: ref(0),
    onSelectionCancel: () => {},
    onbatchAct: () => {},
    treeData: ref([]),
    treeProps: {},
    treeSearchValue: ref(''),
    shopList: ref([]),
    openDialog: () => {},
    handleMenu: () => {},
    handleSave: () => {},
    handleDelete: () => {},
    onQueryChanged: () => {},
    handleSelectionChange: () => {}
  };
}
